using Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Api.Filters;

/// <summary>
/// 全局异常过滤器
/// </summary>
/// <remarks>
/// 捕获所有未处理的异常，并转换为统一的响应格式
/// </remarks>
public class GlobalExceptionFilter : IExceptionFilter
{
    private readonly ILogger<GlobalExceptionFilter> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="logger">日志记录器</param>
    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 异常处理方法
    /// </summary>
    /// <param name="context">异常上下文</param>
    public void OnException(ExceptionContext context)
    {
        // 记录异常日志
        _logger.LogError(context.Exception, "发生未处理的异常: {Message}", context.Exception.Message);

        // 根据异常类型返回不同的响应
        if (context.Exception is BusinessException businessException)
        {
            // 业务异常，返回400状态码
            context.Result = new JsonResult(new
            {
                flag = false,
                message = businessException.ErrorMessage,
                data = (object?)null
            })
            {
                StatusCode = 400
            };
        }
        else
        {
            // 系统异常，返回500状态码
            context.Result = new JsonResult(new
            {
                flag = false,
                message = "服务器内部错误，请稍后重试",
                data = (object?)null
            })
            {
                StatusCode = 500
            };
        }

        // 标记异常已处理
        context.ExceptionHandled = true;
    }
}
